#include "Sprite.h"

LPD3DXSPRITE CSprite::SpriteHandler_ = NULL;
LPDIRECT3DDEVICE9 CSprite::d3dDevice_ = 0;

CSprite::CSprite(wstring filePath, int nRows, int nColumns, int nFrame, int Index)
{
	HRESULT result;
	this->Image_	= NULL;
	this->nColumns_	= nColumns;
	this->nRows_	= nRows;
	this->nFrames_	= nFrame;
	this->Index_	= Index;

	result = D3DXGetImageInfoFromFile(filePath.c_str(),&this->Info_);
	if (result!=D3D_OK)
	{
		//MessageBox(NULL, (L"Unable to load image"), (L"Error"), MB_OK);
		return;
	}
	result = D3DXCreateTextureFromFileEx(
		d3dDevice_,
		filePath.c_str(),
		Info_.Width,
		Info_.Height,
		1,
		D3DUSAGE_DYNAMIC,
		D3DFMT_UNKNOWN,
		D3DPOOL_DEFAULT,
		D3DX_DEFAULT,
		D3DX_DEFAULT,
		D3DCOLOR_XRGB(0,63,63),
		&Info_,
		NULL,
		&Image_);
	if (result!=D3D_OK) 
	{
		return;
	}
	this->FrameInfo_.Width	= (int)((float)this->Info_.Width	/ (float)this->nColumns_);
	this->FrameInfo_.Height = (int)((float)this->Info_.Height	/ (float)this->nRows_);
}


CSprite::~CSprite(void)
{
}

bool CSprite::Render(int from, int to, D3DXVECTOR3 position)
{
	if(to < 0)
		to = nFrames_;
	if (Index_ < from || Index_ > to)
		Index_ = from;
	RECT rec;
	rec = getScrRect();

	D3DXVECTOR3 center((float)this->FrameInfo_.Width/2,(float)this->FrameInfo_.Height,0);

	SpriteHandler_->Draw(
		Image_,
		&rec,
		&center,
		&position, 
		D3DCOLOR_XRGB(255,255,255)
		);

	Index_++;
	if (Index_ >= to) {
		Index_ = from;
		return true;
	}
	else {
		return false;
	}
}

RECT CSprite::getScrRect()
{
	RECT rect;
	rect.left	= (UINT)FrameInfo_.Width  * (Index_ - (int)(Index_/nColumns_) * nColumns_);
	rect.top	= (UINT)FrameInfo_.Height * (int)(Index_ / nColumns_);
	rect.right	= rect.left + (UINT)FrameInfo_.Width  - 1;
	rect.bottom = rect.top  + (UINT)FrameInfo_.Height - 1;
	return rect;
}

D3DXVECTOR3 CSprite::correctImagePosition(D3DXVECTOR3 Position)
{
	D3DXVECTOR4 transformPosition;
	D3DXMATRIX mt;
	D3DXMatrixIdentity(&mt);
	mt._22 = -1.0f;
	mt._41 = Position.x;
	mt._42 = Position.y;
	D3DXVec3Transform(&transformPosition,&Position,&mt);
	D3DXVECTOR3 newPosition(transformPosition.x,transformPosition.y,0.5);
	return newPosition;
}

void CSprite::initializeSpriteHandler(LPD3DXSPRITE spriteHandler)
{
	SpriteHandler_ = spriteHandler;
	SpriteHandler_->GetDevice(&d3dDevice_);
}
